package com.hk.core.autoconfigure.exception.servlet;

import com.hk.commons.JsonResult;
import com.hk.commons.util.SpringContextHolder;
import com.hk.core.authentication.api.AuthenticationException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * spring security 异常处理器
 *
 * @author Kevin
 * @date 2018-09-10 14:17
 */
@RestControllerAdvice
public class SpringSecurityExceptionHandler extends AbstractExceptionHandler {

    /**
     * 无权限访问
     *
     * @param e       e
     * @param request request
     * @return jsonResult
     */
    @ExceptionHandler(value = {AccessDeniedException.class})
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> accessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return JsonResult.forbidden(SpringContextHolder.getMessage("no.permission.access.message"));
    }

    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> authenticationException(AuthenticationException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return JsonResult.unauthorized(SpringContextHolder.getMessage("operation.unauthorized"));
    }

}
